// Copyright (c) 2024 Huawei Technologies Co., Ltd.
// openFuyao is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

package lm

import (
	"fmt"
	"net/url"

	corev1 "k8s.io/api/core/v1"
)

const (
	runtimeLabelKey = "openfuyao.com/container.runtime"
)

var (
	supportedRuntimes = map[string]struct{}{
		"containerd": {},
	}
)

type runtimeInfo struct {
	name string
}

func newRuntimeLabeler(node *corev1.Node) (Labeler, error) {
	runtime, err := getRuntime(node)

	if err != nil {
		return nil, fmt.Errorf("get CRI runtime: %w", err)
	}

	return Labels{runtimeLabelKey: runtime.name}, nil
}

func getRuntime(node *corev1.Node) (runtime *runtimeInfo, err error) {
	uri, err := url.Parse(node.Status.NodeInfo.ContainerRuntimeVersion)
	if err != nil {
		return nil, fmt.Errorf("parse containerRuntimeVersion: %w", err)
	}

	runtime = &runtimeInfo{
		name: uri.Scheme,
	}

	if _, ok := supportedRuntimes[runtime.name]; !ok {
		return nil, fmt.Errorf("unsupported CRI runtime: %v", runtime.name)
	}

	return runtime, nil
}
